package com.shk.controller;



import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.shk.constant.MessageConstant;
import com.shk.constant.RedisMessageConstant;
import com.shk.entity.Result;
import com.shk.pojo.Member;
import com.shk.service.MemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;
    @RequestMapping("/check")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        String code = (String) map.get("validateCode");
       String telephone = (String) map.get("telephone");

        String cd = jedisPool.getResource().get("112");

        if(telephone==null){
           return new Result(false, "faf");
       }
       if(code==null || !code.equals(cd)){
           return new Result(false,"fffffff");
       }
       /*判断数据库中是否已经存在此电话号码 如存在直接登录完成  否则 自动注册为会员后 登陆成功*/
        Member member=null;
        try {
            member=memberService.findByTelephone(telephone);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        if(member==null){
            member=new Member();
            member.setPhoneNumber(telephone);
            UUID password = UUID.randomUUID();
            member.setPassword(password.toString());
            member.setRegTime(new Date());
            memberService.add(member);
        }
        Cookie cookie= new Cookie("login_telephone",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,60*30,json);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
